import groovy.xml.MarkupBuilder
import groovy.xml.XmlUtil
import groovy.xml.StreamingMarkupBuilder
import scriptlerweb.Provider
import scriptlerweb.Script

final String CATALOG_NAME = "scriptlerweb"

def action = params?.action

switch(action){
	
	case 'xml':
		def scripts = dao.ofy().query(Script.class).list()
		out << "<?xml version='1.0'?>"
		def xml = new MarkupBuilder(out)
		html.catalog {
			entrySet{
				scripts.each { s ->
					def p = dao.loadProvider(s.providerId)
					def pName = p.name ? p.name : s.providerId
					entry{
						id("$CATALOG_NAME.${s.id}")
						name(s.name)
						comment(s.comment)
						provider(pName)
						url(s.url)
					}
				}
			}
		}
	
		break
	case 'xmlstream': 
		def scripts = dao.ofy().query(Script.class).list()
		def xml = new StreamingMarkupBuilder().bind{
			mkp.xmlDeclaration()
			catalog {
				entrySet{
					def p = dao.loadProvider(s.providerId)
					def pName = p.name ? p.name : s.providerId
					entry{
						id("$CATALOG_NAME.${s.id}")
						name(s.name)
						comment(s.comment)
						provider(pName)
						url(s.url)
					}
				}
			}
		}
		out.write xml.toString()
	
		break
	default: 
	// default to a list display
		def orderBy = params.orderBy ? params.orderBy : "name"
	
		def scripts = dao.ofy().query(Script.class).order(orderBy).list()
		scripts.each{ s ->
			def p = dao.loadProvider(s.providerId)
			s.providerName = p.name
		}
		request.setAttribute 'scripts', scripts
	
	// switch the order for the next link rendering in the template
	// To specify that the order ought to be in descending order, precede the name with a hyphen (-). Without a hyphen, the order is ascending.
		if(orderBy.startsWith("-")){
			request.setAttribute 'order', ""
		}else{
			request.setAttribute 'order', "-"
		}
	
	
		forward '/catalog.gtpl'
}

